import { reactive, computed } from "vue"
import { useStore } from "vuex"
import { newTopic, getCategory, getGradeCategory, topicList, topicRandList, setGrade, getRandCategory, topicDaily } from "@/api"

export function useTopic(){
	const store = useStore()
	const stateTopic = reactive({
		all: [{ category_name: "全部", category_id: '' }],
		topicCategory: [],
		topicList: [],
		pageSize: 10,
		pageNumber: 1,
		grade: store.state.user.grade,
		currentCategory: '',
		currentTopicCategory: ''
	})
	/**
	 * 获取随机分类
	 */
	const useGetRandCategoryList = (params = {}) => {
		return new Promise((resolve, reject) => {
			getRandCategory({ grade_id: stateTopic.grade, category_id: stateTopic.currentCategory || '', mode: '10' }).then(res => {
				stateTopic.topicCategory = [...stateTopic.all, ...res.content]
				resolve()
			})
		})
	}
	
	/**
	 * 获取课程分类
	 */
	const useGetCourseCategory = () => {
		return new Promise((resolve, reject) => {
			getGradeCategory({ grade_id: stateTopic.grade, category_id: stateTopic.currentCategory || '', mode: '10' }).then(res => {
				stateTopic.topicCategory = [...stateTopic.all, ...res.content]
				resolve()
			})
		})
	}
	
	/**
	 * 获取分类
	 */
	const useGetCategoryList = () => stateTopic.currentCategory ? useGetCourseCategory() : useGetRandCategoryList()
	
	/**
	 *获取题目 
	 */
	const userGetTopicList = (params = {}) => {
		return new Promise((resolve, reject) => {
			topicList({
				'grade_id': stateTopic.grade,
				'category_id': stateTopic.currentCategory,
				'sub_category_id': stateTopic.currentTopicCategory,
				'pageSize': stateTopic.pageSize,
				'pageNumber': stateTopic.pageNumber,
				// 'field': fielsItem.value?.field || null
			}).then(res => {
				stateTopic.topicList = res.content?.data || []
				resolve(stateTopic.topicList)
			}).catch(() => {
				reject()
			})
		})
	}
	
	/**
	 * 获取随机题目
	 */
	const useGetRandTopicList = (params = {}) => {
		return new Promise((resolve, reject) => {
			topicRandList({
				'category_id': stateTopic.currentCategory,
				'sub_category_id': stateTopic.currentTopicCategory,
				'grade_id': stateTopic.grade,
				// 'field': fielsItem.value?.field || null,
				value: params?.value,
				pageSize: params?.pageSize
			}).then(res => {
				stateTopic.topicList = res.content?.data || []
				resolve(stateTopic.topicList)
			})
		})
	}
	
	return {
		stateTopic,
		userGetTopicList,
		useGetRandTopicList,
		useGetRandCategoryList,
		useGetCourseCategory,
		useGetCategoryList
	}
	
}